<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// | 该文件的开源协议以所在项目的LICENSE文件为准，请遵守开源协议要求
// +----------------------------------------------------------------------
// | 充值
// +----------------------------------------------------------------------
namespace app\finance\model;

use Inphp\Core\Db\PDO\Model;

class RechargeModel extends Model
{
    /**
     * 表名
     * @var string
     */
    protected string $tableName = "finance_recharge";

    /**
     * 主键
     * @var string
     */
    protected string $primaryKey = "orderId";

    /**
     * 支付异步通知
     * 提现扣除资产 成功时
     * @param int $orderId
     * @param int $cashierId
     * @param float|int $payedAmount
     */
    public static function payedNotify(int $orderId, int $cashierId, float|int $payedAmount)
    {
        $order = self::getRowByPrimaryKey($orderId);
        if (empty($order)) {
            return;
        }
        if ($order["payed"] == 1) {
            return;
        }
        if (!empty($order["cashierId"])) {
            return;
        }
        $time = date("Y-m-d H:i:s");
        $db = self::emptyQuery()
            ->where("orderId", $orderId)
            ->set("payedTime", $time)
            ->increment("payedAmount", $payedAmount)
            ->set("cashierId", $cashierId)
            ->setRaw("payed", "if(`amount`<=`payedAmount`, 1, 0)");
        if ($db->update() && $db->getAffectRows() > 0) {
            //标记为已通知
            CashierModel::payedNotified($cashierId);
            //如果已完成支付，账户资产增加
            if ($order["amount"] <= bcadd($order["payedAmount"], $payedAmount, 2)) {
                BalanceModel::plus($order["uid"], $order["balance"], $order["quantity"], "recharge", null, $orderId);
            }
        }
    }

    public static function refundNotify(int $orderId, int $refundId, float|int $refundAmount)
    {
        $order = self::getRowByPrimaryKey($orderId);
        if (empty($order)) {
            return;
        }
        if ($order["payed"] == 0) {
            return;
        }
        if (empty($order["cashierId"])) {
            return;
        }
        if (!empty($order["refundId"]) && in_array($refundId, explode(",", $order["refundId"]))) {
            return;
        }
        $db = self::emptyQuery()
            ->where("orderId", $orderId)
            ->set([
                "refund"        => 1,
                "refundTime"    => date("Y-m-d H:i:s")
            ])
            ->increment("refundAmount", $refundAmount)
            ->setRaw("refundId", "if(`refundId` is null or `refundId`='', '{$refundId}', concat(`refundId`, ',{$refundId}'))");
        if ($db->update()) {
            $quantity = bcdiv($refundAmount, $order["price"], 0);
            BalanceModel::minus($order["uid"], $order["balance"], $quantity, "refund");
        }
    }
}